package com.sso.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.sso.common.ConstantDate;
import com.tools.util.DESUtils;
import com.tools.util.PropertiesUtils;
import com.tools.util.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

/**
 * session管理器
 * 重写getSessionId方法
 * @author Admin
 *
 */
public class MySessionManager extends DefaultWebSessionManager {
	private String domain = PropertiesUtils.getValueByProperty("domain", "/shiro.properties");
	/**
	 * 此主方法可以接收来自cookie中的sessionid与外部调用参数传来sessionid并切换到对应的会话
	 * 如都不存在sessionid则交由shiro原类处理
	 */
	public MySessionManager(){
		this.setSessionValidationInterval(1000*60);
	}
	@Override
	protected Serializable getSessionId(ServletRequest request,	ServletResponse response) {
        // 其实这里还可以使用如下参数：cookie中的session名称：如：JSESSIONID=xxx,路径中的 ;JESSIONID=xxx，但建议还是使用 __sid参数。
		javax.servlet.http.Cookie[] cookies = ((HttpServletRequest)request).getCookies();
		String sid = request.getParameter("token");
		if(StrUtils.isEmpty(sid)){
			if(cookies !=null){
				for(javax.servlet.http.Cookie c : cookies){
					if(c.getName().equals(domain)){
						sid=c.getValue();
					}
				}
			}
		}else{
			try {
				DESUtils des = new DESUtils(ConstantDate.DESPassword.SSO_TOKEN);
				sid =des.encrypt(sid);
			} catch (Exception e) {
				e.printStackTrace();
				sid="";
			}
		}
		if (StringUtils.isNotBlank(sid)) {
			// 设置当前session状态
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroHttpServletRequest.URL_SESSION_ID_SOURCE); // session来源与url
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sid);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return sid;
		}else{
			return super.getSessionId(request, response);
		}
	}

}
